/*
 * TextureList.cpp
 *
 *  Created on: 2012/07/06
 *      Author: weihe
 */

#include <iostream>
#include <cstdlib>
#include "TextureList.h"
#include "stb_image.h"
#include <gl/glut.h>
#include "utility.h"

namespace object {

TextureList::TextureList(int size) :
		size(size) {
	assert(size > 0);
	glEnable(GL_TEXTURE_2D);
	textures = new unsigned int[size];
	for (int i = 0; i < size; i++) {
		textures[i] = getUid();
	}
	glGenTextures(size, textures);
}

void TextureList::load(int idx, const char *file) {
//	cout << "load file: " << file << " to index: " << idx << endl;
	int width, height, comp;
//	unsigned char *image = stbi_load(file, &width, &height, &comp, 4);
	unsigned char *image = stbi_load(file, &width, &height, &comp, 3);
	if (!image) {
		cerr << "can't open file: " << file << endl;
		return;
	}
	glBindTexture(GL_TEXTURE_2D, textures[idx]);
//	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
//			GL_UNSIGNED_BYTE, image);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
				GL_UNSIGNED_BYTE, image);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	stbi_image_free(image);
}

void TextureList::load(const char **files) {
	for (int i = 0; i < size; i++) {
		if (files[i][0] == '\0') {
			break;
		}
		load(i, files[i]);
	}
}

void TextureList::bind(int idx) {
	glBindTexture(GL_TEXTURE_2D, textures[idx]);
}

TextureList::~TextureList() {
	glDeleteTextures(size, textures);
	delete[] textures;
}

} /* namespace object */
